function Dialog(selector, opts) {
    this.opts = { ...opts };
    this.$el = $(selector);
    this.$el.on('click', '.dialog-close-btn', () => this.close());
}

Dialog.prototype.open = open;
Dialog.prototype.close = close;

function open() {
    this.$el.show();
    disableBodyScroll.call(this);
    const { onOpen } = this.opts;
    if (onOpen) {
        setTimeout(onOpen, 0);
    }
}

function close() {
    this.$el.hide();
    enableBodyScroll.call(this);
    const { onClose } = this.opts;
    onClose && onClose();
}

function disableBodyScroll() {
    this.scrollable = document.body.scrollHeight > document.body.offsetHeight;
    if (this.scrollable) {
        this.y = window.scrollY;
        document.body.style.top = `-${this.y}px`;
        document.body.style.position = 'fixed';
        document.body.style.overflowY = 'scroll';
        document.body.style.width = `100%`;
    }
}

function enableBodyScroll() {
    if (this.scrollable) {
        document.body.style.top = '';
        document.body.style.position = '';
        document.body.style.overflowY = '';
        window.scrollTo(0, this.y);
    }
}

export default Dialog;
